/**
 * Copyright [2012-2013] [Guðmundur Björn Birkisson]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. Copyright [2012-2013] [Guðmundur Björn Birkisson]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * ---------------------------------------------------------------------------
 * 
 * Class name:  GameCommandThread
 * 
 * Description of class:
 * 
 * Implements a thread that pauses the Morpho VM while animating Karel the 
 * robot.
 * 
 */

package karel.gamelogic;

import java.util.logging.Level;
import java.util.logging.Logger;
import karel.gamelogic.commands.KarelCommand;

public class GameCommandThread extends Thread {

    private KarelCommand command;
    private volatile boolean isRunning;
    private volatile boolean executingCommand;

    public GameCommandThread(String name) {
        super(name);
        isRunning = true;
        executingCommand = false;
    }

    public synchronized Object issueCommand(KarelCommand command) {
        this.command = command;
        executingCommand = true;
        
        try {
            wait();
        } catch (InterruptedException ex) {
            Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
        }

        return command.getCommandReturnValue();
    }

    public synchronized void killThread() {
        isRunning = false;
    }

    @Override
    public void run() {
        while (isRunning) {
            if (executingCommand) {
                if (command.isCommandDone()) {
                    executingCommand = false;
                    synchronized (this) {
                        notifyAll();
                    }
                } else {
                    command.commandUpdate();
                }
            }
        }
    }
}
